# -*- coding: utf-8 -*-

from songaudio import SongAudio
from songirc import SongIrc
from songmanager import SongManager

from PyQt4.QtCore import QObject
from PyQt4 import QtCore


class Song(QObject):
    updateTime = QtCore.pyqtSignal(int)      # 更新信号
    playFinished = QtCore.pyqtSignal()       # 歌曲结束信号
    ircUpdate = QtCore.pyqtSignal(str)  # 歌词更新信号

    def __init__(self):
        super(Song, self).__init__()
        self._url = ''
        self._audio = SongAudio()  # 播放器初始化
        self._irc = SongIrc()      # 歌词类初始化

        self._audio.media_obj.tick.connect(self._on_update)
        self._audio.media_obj.finished.connect(self._on_finished)

    @property
    def url(self):
        return self._url

    @url.setter
    def url(self, value):
        self._url = value
        self._audio.setUrl(value)
        ircurl = SongManager.getSongIrc(value)
        self._irc.setUrl(QtCore.QString.fromUtf8(ircurl).__str__())

    def play(self):
        self._audio.play()

    def pause(self):
        self._audio.pause()

    def stop(self):
        self._audio.stop()

    def clear(self):
        self._audio.media_obj.clear()
        self._irc.clear()

    @property
    def audio(self):
        return self._audio

    def _on_update(self, time):
        self.updateTime.emit(time)
        irc_block = self._irc.getBlock(time)  # 获取歌词
        if irc_block:
            self.ircUpdate.emit(irc_block)   # 发送信号

    def _on_finished(self):
        self.playFinished.emit()                  # 发送歌曲结束信号



